package app.netant.galgame.hgamecn;

import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import app.netant.NetAntBase;
import cn.lily.com.db.DBFactory;
import cn.lily.com.db.container.reader.DataTable;
import cn.lily.com.enviroment.Enviroment;
import cn.lily.com.lang.Basic;
import cn.lily.com.lang.number.MathUtil;

/**
 * Hgamecn 分页处理
 * @author JiaJ
 * @date 2018年6月13日
 *
 */
public class HgamecnAntPage extends NetAntBase {
	
	public HgamecnAntPage(String netSite, int timeout) {
		super(netSite, timeout);
	}
	
	public HgamecnAntPage(String netSite) {
		super(netSite);
	}
	
	public void analyse(){
		
		Elements activePart = document.select(".container-fluid .row-fluid #content "
				                            + ".row-fluid .block .block-content.collapse.in "
				                            + "ul[id='subjects'] li.media");
		
		for(int i=0;i<activePart.size();i++){
			
			Enviroment.getEnv().getLogBean().beginLog();
			
			HgamecnEntity entity = new HgamecnEntity();
			
			String href = "";
			
			try {
				
				Element activeEle = activePart.get(i);	
				
				String title = this.getString(activeEle.select(".media-body .media-heading").text());		
				href = activeEle.select(".media-body .media-heading a").get(0).attr("href");
				if(href.startsWith("/")){
					href = "https://www.2dfan.com"+href;
				}
				
				System.out.println(href+"开始处理.............");
				
				DataTable dataTable = this.getDBManager().executeQueryTable("select * from ${schema}.LEO_HGAMECN_INFO where GAME_URL='"+href+"'");
				if(dataTable.next()){
					continue;
				}
				
				entity.setGameName(title);
				entity.setGameUrl(href);
				
				Elements tagParts = activeEle.select(".media-body p.tags span");
				for(int j=0;j<tagParts.size();j++){				
					String tag = tagParts.get(j).text();				
					String[] tags = Basic.split(tag, ":","：");
					
					if(tags.length == 2){
						entity.setTag(tags[0], this.getString(tags[1]));
					}
				}
				
				if(entity.isGameIsMemo()){
					HgamecnAntDetail detail = new HgamecnAntDetail(href);
					entity.setGameMemo(detail.getMemo());
					detail.analyseTags(entity);
				}
				
				entity.insert();
				
				this.getDBManager().commit();
				
			} catch (Exception e) {
				
				e.printStackTrace();
				
				if(href.startsWith("http")){				
					this.getDBManager().executeUpdate("insert into ${schema}.LEO_HGAMECN_EXCEP (EXCEP_ID,EXCEP_URL,EXCEP_LEVEL) "
							+ "values ('"+System.currentTimeMillis()+""+MathUtil.random(3)+"','"+href+"','2')");
				}
				
				continue;
				
			}
			
			Enviroment.getEnv().getLogBean().endLog();
			
			
		}
		
	}
	
	public static void main(String[] args) {
		Enviroment.createEnv();
		HgamecnAntPage page = new HgamecnAntPage("https://www.2dfan.com/subjects");
		page.analyse();
	}
}
